package logs

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"shen/gotask/rocketmq/config"
	"time"
)

var (
	traceStr     = "[Info] | %v"
	traceWarnStr = "[Warn] | %v"
	traceErrStr  = "[Error] | %v"
)

type Logs struct {
	IsOpenLogs bool
	IsConsole  bool
	Level      Level
}

type Level int8

const (
	LevelInfo Level = iota
	LevelWarn
	LevelError
)

func NewLogs() *Logs {
	return &Logs{
		IsOpenLogs: config.Config.Logs.IsOpenLogs,
		IsConsole:  config.Config.Logs.IsConsole,
		Level:      getLogLevel(config.Config.Logs.LogsLevel),
	}
}
func getLogLevel(level string) Level {
	switch level {
	case "info":
		return LevelInfo
	case "warning":
		return LevelWarn
	case "error":
		return LevelError
	default:
		return LevelInfo
	}
}

func (l Logs) Info(data ...any) {
	if l.getLogsIsOpen(LevelInfo) {
		l.printf(traceStr, data...)
	}
}
func (l Logs) Warning(data ...any) {
	if l.getLogsIsOpen(LevelWarn) {
		l.printf(traceWarnStr, data...)
	}
}
func (l Logs) Error(data ...any) {
	if l.getLogsIsOpen(LevelError) {
		l.printf(traceErrStr, data...)
	}
}

func (l Logs) InfoFormat(format string, data ...any) {
	format = fmt.Sprintf(format, data...)
	if l.getLogsIsOpen(LevelInfo) {
		l.printf("[Info] | %s", format)
	}
}
func (l Logs) WarningFormat(format string, data ...any) {
	format = fmt.Sprintf(format, data...)
	if l.getLogsIsOpen(LevelWarn) {
		l.printf("[Warning] | %s", format)
	}
}
func (l Logs) ErrorFormat(format string, data ...any) {
	format = fmt.Sprintf(format, data...)
	if l.getLogsIsOpen(LevelError) {
		l.printf("[Error] | %s", format)
	}
}

func (l Logs) getLogsIsOpen(logsLevel Level) bool {
	if !l.IsOpenLogs {
		return false
	}

	if logsLevel >= l.Level {
		return true
	}

	return false
}

func (l Logs) printf(format string, v ...any) {
	if l.IsConsole {
		lo := log.New(os.Stdout, "\r\n", log.LstdFlags)
		lo.Printf(format, v...)
	} else {
		nowTime := time.Now()
		dir := config.Config.Logs.LogsPath + "/" + nowTime.Format("20060102")
		absDir, err := filepath.Abs(dir)

		file := absDir + "/" + "rocketmq.log"

		_, err = os.Stat(absDir)

		if os.IsNotExist(err) {
			// 如果目录不存在，使用os.MkdirAll创建目录，它会递归创建多级目录
			err = os.MkdirAll(absDir, 0755)
			if err != nil {
				lo1 := log.New(os.Stdout, "\r\n", log.LstdFlags)
				lo1.Printf(format, v...)
			}
		}
		openFile, err := os.OpenFile(file, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
		defer openFile.Close()
		if err != nil {
			return
		}
		lo := log.New(openFile, "", log.LstdFlags)
		lo.Printf(format, v...)
	}
}
